package controllers

import (
	"encoding/json"
	"fmt"
	"log"
	"loghub/db"
	"loghub/filters"
	"loghub/model"
	"reflect"
	"time"

	"net/http"

	"github.com/kataras/iris/v12"
	uuid "github.com/satori/go.uuid"
)

// RegisterIndexController 注册控制器
func RegisterIndexController(app *iris.Application) {
	// 首页, 登录页
	app.Get("/", func(ctx iris.Context) {
		// 判断用户是否登录
		var sid = ctx.GetCookie("sid")
		if len(sid) > 0 {
			var userSession = model.UserSession{}
			var sql = "select * from user_session where sid='%s'"
			var querystring = fmt.Sprintf(sql, sid)
			err := db.QueryStructByReflect(querystring, &userSession)
			if err != nil {
				log.Println(err)
			}
			if userSession.Sid == sid && int(time.Now().Sub(userSession.CreateTime).Seconds()) < userSession.ExpireTime {
				fmt.Println("当前用户已登录")
				ctx.Redirect("/home/index")
				return
			}
		}

		if err := ctx.View("login.html"); err != nil {
			ctx.Application().Logger().Info(err.Error())
		}
	})

	// 网站图标
	app.Get("/favicon.ico", func(ctx iris.Context) {
		ctx.Redirect("/wwwroot/favicon.ico", 301)
	})

	// 登录api
	app.Post("/login", func(ctx iris.Context) {
		var user model.User
		var username = ctx.FormValue("username")
		var pwd = ctx.FormValue("password")
		var sql = "select * from user where username='%s' and password='%s'"
		var querystring = fmt.Sprintf(sql, username, pwd)
		db.QueryStructByReflect(querystring, &user)

		jsondata, err := json.Marshal(user)
		if err != nil {
			log.Println(err)
		}
		if username == user.UserName && pwd == user.Password {
			// 将sid写入Redis或者数据库临时缓存
			var sid = uuid.NewV4().String()
			var userSession = model.UserSession{
				Sid:        sid,
				UserID:     user.ID,
				UserName:   user.UserName,
				CreateTime: time.Now(),
				ExpireTime: 60 * 60 * 24,
			}
			sql = "insert into user_session values ('%s','%d','%s','%s','%d')"
			querystring = fmt.Sprintf(sql, userSession.Sid, userSession.UserID, userSession.UserName, userSession.CreateTime.Format("2006-01-02 15:04:05"), userSession.ExpireTime)
			exexResult, err := db.ExecSQL(querystring)
			if err != nil {
				log.Println(err)
			}
			fmt.Println(exexResult)
			ctx.SetCookie(&http.Cookie{
				Name:     "sid",
				Value:    sid,
				Path:     "/",
				HttpOnly: true,
			})
		}

		ctx.WriteString(string(jsondata))
	})

	// 需要验证cookie的授权, 分组action
	app.PartyFunc("/home", func(p iris.Party) {
		p.Use(filters.AuthHandle)

		// 首页, 显示视图静态html页面
		p.Get("/index", func(ctx iris.Context) {
			err := ctx.View("index.html")
			if err != nil {
				log.Println(err)
			}
		})

		// 获取所有项目列表
		p.Get("/project_data", func(ctx iris.Context) {
			// 表单校验拦截器
			var sql = "select * from project_info order by CreateTime"
			var search = ctx.URLParam("search")
			if len(search) > 0 {
				sql = fmt.Sprintf("select * from project_info where ProjectName like '%s' order by CreateTime", "%"+search+"%")
			}

			exexResult, err := db.QueryStructListByReflect(sql, reflect.TypeOf(model.ProjectInfo{}))
			if err != nil {
				log.Println(err)
				ctx.JSON(model.ResponseData{State: false, Message: "查询失败", Error: err.Error(), HTTPCode: 500})
				return
			}
			ctx.JSON(exexResult)
		})

		// 新增项目
		p.Post("/project", func(ctx iris.Context) {
			var project model.ProjectInfo
			if err := ctx.ReadForm(&project); err != nil {
				log.Println(err)
				ctx.JSON(model.ResponseData{State: false, Message: "创建失败", Error: err.Error(), HTTPCode: 400})
				return
			}
			var userCtx = ctx.Values().Get("user")
			project.ProjectID = uuid.NewV4().String()
			project.CreateTime = time.Now()
			project.Cretor = (userCtx.(model.UserSession)).UserName
			// 表单校验拦截器
			var sql = "insert into project_info values ('%s','%s','%s','%s','%s')"
			var querystring = fmt.Sprintf(sql, project.ProjectID, project.ProjectName, project.ProjectPlatform, project.Cretor, project.CreateTime.Format("2006-01-02 15:04:05"))
			exexResult, err := db.ExecSQL(querystring)
			if err != nil {
				log.Println(err)
				ctx.JSON(model.ResponseData{State: false, Message: "创建失败", Error: err.Error(), HTTPCode: 500})
				return
			}
			fmt.Println(exexResult)
			ctx.JSON(model.ResponseData{State: true, Message: "创建成功"})
		})

		// 编辑项目
		p.Post("/editProject", func(ctx iris.Context) {
			var project model.ProjectInfo
			if err := ctx.ReadForm(&project); err != nil {
				log.Println(err)
				ctx.JSON(model.ResponseData{State: false, Message: "参数错误", Error: err.Error(), HTTPCode: 400})
				return
			}
			if len(project.ProjectID) <= 0 || len(project.ProjectName) <= 0 || len(project.ProjectPlatform) <= 0 {
				log.Println("参数错误")
				ctx.JSON(model.ResponseData{State: false, Message: "修改失败", HTTPCode: 400})
				return
			}

			var userCtx = ctx.Values().Get("user")
			var username = (userCtx.(model.UserSession)).UserName
			var sql = "update project_info set ProjectName='%s', ProjectPlatform='%s' where ProjectID='%s' and Cretor='%s'"
			var querystring = fmt.Sprintf(sql, project.ProjectName, project.ProjectPlatform, project.ProjectID, username)
			execResult, err := db.ExecSQL(querystring)
			if err != nil {
				log.Println(err)
				ctx.JSON(model.ResponseData{State: false, Message: "参数错误", Error: err.Error(), HTTPCode: 400})
				return
			}
			fmt.Println(execResult)
			ctx.JSON(model.ResponseData{State: true, Message: "修改成功"})
		})

		// 获取日志数据列表
		p.Get("/findlogdatawithpager", func(ctx iris.Context) {
			var pid = ctx.URLParam("pid")
			var rows = ctx.URLParamIntDefault("rows", 10)
			var page = ctx.URLParamIntDefault("page", 1)
			var sort = ctx.URLParamDefault("sortOrder", "asc")
			if len(pid) < 32 {
				ctx.JSON(model.ResponseData{State: false, Message: "参数错误", HTTPCode: 400})
				return
			}
			var sql = fmt.Sprintf("select * from log_detail_data where ProjectID='%s' order by CreateTime %s Limit %d,%d", pid, sort, (page-1)*rows, rows)
			exexResult, err := db.QueryStructListByReflect(sql, reflect.TypeOf(model.LogDetailData{}))
			if err != nil {
				log.Println(err)
				ctx.JSON(model.ResponseData{State: false, Message: "查询失败", Error: err.Error(), HTTPCode: 500})
				return
			}

			sql = fmt.Sprintf("select count(*) from log_detail_data where ProjectID='%s'", pid)
			dataCount, rawValue, err := db.QueryScalarFloat64(sql)
			if err != nil {
				log.Println(err, rawValue)
				ctx.JSON(model.ResponseData{State: false, Message: "查询失败", Error: err.Error(), HTTPCode: 500})
				return
			}
			var data = make(map[string]interface{})
			data["total"] = dataCount
			data["rows"] = exexResult
			ctx.JSON(data)
		})

		p.Get("/logtrace", func(ctx iris.Context) {
			var traceID = ctx.URLParam("traceid")
			if len(traceID) < 32 {
				ctx.JSON(model.ResponseData{State: false, Message: "参数错误", HTTPCode: 400})
				return
			}

			var sql = fmt.Sprintf("select * from log_detail_data where TraceID='%s'", traceID)
			var logDetailData = model.LogDetailData{}
			err := db.QueryStructByReflect(sql, &logDetailData)
			if err != nil {
				log.Println(err)
				ctx.JSON(model.ResponseData{State: false, Message: "查询失败", Error: err.Error(), HTTPCode: 500})
				return
			}
			sql = fmt.Sprintf("select * from log_trace_info where TraceID='%s'", traceID)
			logTraceList, err := db.QueryStructListByReflect(sql, reflect.TypeOf(model.LogTraceInfo{}))
			if err != nil {
				log.Println(err, logTraceList)
				ctx.JSON(model.ResponseData{State: true, Message: "查询成功,但logTraceList为空", Data: logDetailData})
				return
			}
			for _, v := range logTraceList {
				if trace, ok := v.(model.LogTraceInfo); ok {
					logDetailData.LogTraceList = append(logDetailData.LogTraceList, trace)
				}
			}
			ctx.JSON(model.ResponseData{State: true, Message: "查询成功", Data: logDetailData})
		})
	})
}
